const path = require('path');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const os = require('os');
const child_process = require('child_process');
const { exec } = require('child_process');
const fs = require('fs');


function clearDirectory(directoryPath) {
  const isDirectoryExists = fs.existsSync(directoryPath);

  if (!isDirectoryExists) {
    fs.mkdirSync(directoryPath);
  } else {
    fs.readdirSync(directoryPath).forEach((file) => {
      const filePath = path.join(directoryPath, file);
      if (fs.lstatSync(filePath).isDirectory()) {
        return;
      } else {
        try {
          fs.unlinkSync(filePath); // 删除文件
        } catch {
          console.log(`can't del file ${filePath}`);
        }
      }
    });
  }
}
function compileServerCallback() {
    return (error, stdout, stderr) => {
        if (error) {
            console.error(`smartPerf compile failed: ${error}`);
            return;
        }
        console.info(`${stdout}`);
        console.info(`${stderr}`);
        console.log("smartPerf compile success");
    }
}

function buildMultiPlatform() {
  const outPath = path.normalize(path.join(__dirname, '/', 'dist'));
  let serverSrc = path.normalize(path.join(__dirname, "/server/"));
  if (os.type() === "Windows_NT") {
    child_process.exec("cd " + serverSrc + " && go build  -o " +
        outPath + " ./main.go", compileServerCallback());
} else if (os.type() == "Darwin") {
    child_process.exec("cd " + serverSrc + " && go build -o " +
        outPath + "/main ./main.go", compileServerCallback());
} else {
    child_process.exec("cd " + serverSrc + " && go build -o " +
        outPath + "/main ./main.go", compileServerCallback());
}
  }

//compile server
((flag) => {
  if (!flag) {
    return;
  }
  console.log('start compile server');
  let outPath = path.normalize(path.join(__dirname, '/', 'dist'));
  clearDirectory(outPath);
  buildMultiPlatform();
})(true);

module.exports = {
    // 入口
    entry: './src/index.ts',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].[chunkhash].bundle.js',
        clean: false,
    },
    devServer: {
        open: true,
        host: 'localhost',
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: 'index.html',
        }),
        new CleanWebpackPlugin({
            verbose: true,
            cleanOnceBeforeBuildPatterns: ['!main'],
        }),
        new CopyWebpackPlugin({
            patterns: [
                {
                    from: './src/statistics',
                    to: 'statistics',
                },
                {
                    from: './src/img',
                    to: 'img',
                },
                {
                    from: './src/base-ui/icon.svg',
                    to: 'base-ui/icon.svg',
                },
                {
                    from: './server/version.txt',
                    to: 'version.txt',
                },
                {
                  from: './server/config.ini',
                  to: 'config.ini',
                },
            ],
        }),
        // Add your plugins here
        // Learn more about plugins from https://webpack.js.org/configuration/plugins/
    ],
    module: {
        rules: [
            {
                test: /\.(ts|tsx)$/i,
                loader: 'ts-loader',
                exclude: ['/node_modules/'],
            },
            {
                test: /\.css$/i,
                use: ['style-loader', 'css-loader', 'postcss-loader'],
            },
            {
                test: /\.(eot|svg|ttf|woff|woff2|png|jpg|gif)$/i,
                type: 'asset',
            },

            // Add your rules for custom modules here
            // Learn more about loaders from https://webpack.js.org/loaders/
        ],
    },
    resolve: {
        extensions: ['.tsx', '.ts', '.jsx', '.js', '...'],
        fallback: {
            fs: false,
            tls: false,
            net: false,
            zlib: false,
            http: false,
            https: false,
            stream: false,
            crypto: false,
            path: false, //if you want to use this module also don't forget npm i crypto-browserify
        },
    },
    mode: 'development'
}
